﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Maticsoft.Common;
using System.Text;

namespace Admin.Material
{
    public partial class Manage : System.Web.UI.Page
    {
        ChinaSoft.Model.Model_tb_MidSoft_FileForm modelFileForm = new ChinaSoft.Model.Model_tb_MidSoft_FileForm();
        ChinaSoft.BLL.BLL_tb_MidSoft_FileForm bllFileForm = new ChinaSoft.BLL.BLL_tb_MidSoft_FileForm();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.Params["ProjectId"] != null && Request.Params["ProjectId"].Trim() != "")
                {
                    int ProjectInfoId = ChinaSoft.Common.Input.SetInt(Request.Params["ProjectId"]);
                    BindData();
                }
                if (Request.Params["id"] != null && Request.Params["id"].Trim() != "")
                {
                    int ISOId = ChinaSoft.Common.Input.SetInt(Request.Params["id"]);
                    BindISOInfo(ISOId);
                }
            }
        }
        private void BindISOInfo(int isoId)
        {
            modelFileForm = bllFileForm.GetModel(isoId);
            txtFormName.Value = modelFileForm.FormName;
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            string strErr = "";

            if (this.txtFormName.Value.Trim()=="")
            {
                strErr += "表单名称不能为空！\\n";
            }
            if (strErr != "")
            {
                MessageBox.Show(this, strErr);
                return;
            }
            int ProjectInfoId = ChinaSoft.Common.Input.SetInt(Request.Params["ProjectId"]);
            string FormName = this.txtFormName.Value.Trim();
            string FileFolder = "";
            string FileSaveName = "";
            string FileName = "";
            #region 上传文档
            if (FileUpload1.HasFile)
            {
                string result = ChinaSoft.Common.UpFile.UpDocFile(FileUpload1, Server.MapPath("/Uploads"), "", 5);
                if (result.Contains("错误"))
                {
                    Maticsoft.Common.MessageBox.Show(this, result);
                    return;
                }
                else
                {
                    FileFolder = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString();
                    FileSaveName = result;
                    FileName = FileUpload1.FileName;
                }
            }
            #endregion
            string FormType = "1";
            DateTime CreateTime = DateTime.Now;
            int CreateUserId = ChinaSoft.Common.Input.SetInt(Session["currentUserID"]);
            if (Request.Params["id"] != null && Request.Params["id"].Trim() != "")
            {
                #region 更新
                int FileFormId = ChinaSoft.Common.Input.SetInt(Request.Params["id"]);
                modelFileForm = bllFileForm.GetModel(FileFormId);
                modelFileForm.FormName = FormName;
                if (FileFolder != "" || string.IsNullOrEmpty(modelFileForm.FileFolder))
                {
                    modelFileForm.FileFolder = FileFolder;
                    modelFileForm.FileName = FileName;
                    modelFileForm.FileSaveName = FileSaveName;
                }
                bllFileForm.Update(modelFileForm);
                #endregion
            }
            else
            {
                #region 添加
                modelFileForm.ProjectInfoId = ProjectInfoId;
                modelFileForm.FormName = FormName;
                modelFileForm.FileFolder = FileFolder;
                modelFileForm.FileSaveName = FileSaveName;
                modelFileForm.FileName = FileName;
                modelFileForm.FormType = FormType;
                modelFileForm.CreateTime = CreateTime;
                modelFileForm.CreateUserId = CreateUserId;
                bllFileForm.Add(modelFileForm);
                #endregion
            }
            Response.Redirect("/Material/Manage.aspx?ProjectId=" + ProjectInfoId);
            //Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<script language='javascript'>window.location='/ISOForm/ISOManage.aspx?ProjectId=" + ProjectInfoId + "'</script>");
        }

        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void imgBtnDel_Click(object sender, ImageClickEventArgs e)
        {
            string idlist = GetSelIDlist();
            if (idlist.Trim().Length == 0)
                return;
            //bllFileForm.DeleteList(idlist);
            BindData();
        }

        #region gridView
        public void BindData()
        {
            #region
            //if (!Context.User.Identity.IsAuthenticated)
            //{
            //    return;
            //}
            //AccountsPrincipal user = new AccountsPrincipal(Context.User.Identity.Name);
            //if (user.HasPermissionID(PermId_Modify))
            //{
            //    gridView.Columns[6].Visible = true;
            //}
            //if (user.HasPermissionID(PermId_Delete))
            //{
            //    gridView.Columns[7].Visible = true;
            //}
            #endregion
            StringBuilder strWhere = new StringBuilder();
            strWhere.AppendFormat(" and FormType='1'");
            if (Request.Params["ProjectId"] != null && Request.Params["ProjectId"].Trim() != "")
            {
                strWhere.AppendFormat(" and ProjectInfoId='{0}'", Request.Params["ProjectId"]);
            }
            if (hiddenSearchName.Value.Trim() != "")
            {
                strWhere.AppendFormat(" and FormName like '%{0}%'", hiddenSearchName.Value.Trim());
            }
            try
            {
                ChinaSoft.BLL.Common.Pager.BindGridView(gridView, AspNetPager1, "tb_MidSoft_FileForm", "FileFormId", "*", strWhere.ToString(), "CreateTime desc", "");
            }
            catch (Exception ex)
            {
                Response.Write("数据库错误：" + ex.Message);
                Response.End();
            }
        }
        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            BindData();
        }
        protected void gridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gridView.PageIndex = e.NewPageIndex;
            BindData();
        }
        protected void gridView_OnRowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                e.Row.Cells[0].Text = "<input type=\"checkbox\" id=\"cbSelectAll\" name=\"cbSelectAll\" onclick=\"javascript:checkJs(this.checked);\" />";
            }
        }
        protected void gridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                LinkButton linkbtnDel = (LinkButton)e.Row.FindControl("LinkButton1");
                if (linkbtnDel.Attributes["BindData"].ToString() == ChinaSoft.Common.Input.SetString(Session["currentUserID"]))
                    linkbtnDel.Visible = true;
                else
                    linkbtnDel.Visible = false;
                //LinkButton linkbtnDel = (LinkButton)e.Row.FindControl("LinkButton1");
                //linkbtnDel.Attributes.Add("onclick", "return confirm(\"你确认要删除吗\")");

                //object obj1 = DataBinder.Eval(e.Row.DataItem, "Levels");
                //if ((obj1 != null) && ((obj1.ToString() != "")))
                //{
                //    e.Row.Cells[1].Text = obj1.ToString();
                //}

            }
        }
        protected void gridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            //#warning 代码生成警告：请检查确认真实主键的名称和类型是否正确
            int ID = (int)gridView.DataKeys[e.RowIndex].Value;
            modelFileForm = bllFileForm.GetModel(ID);
            if (modelFileForm != null)
            {
                int createUserId = 0;
                if (Session["currentUserID"] != null && Session["currentUserID"].ToString() != "")
                    createUserId = ChinaSoft.Common.Input.SetInt(Session["currentUserID"]);

                if (modelFileForm.CreateUserId == createUserId)
                {
                    bllFileForm.Delete(ID);
                }
                else
                    Maticsoft.Common.MessageBox.Show(this, "这不是您的ISO表单，您没有权限删除该ISO表单");
            }
            else
                Maticsoft.Common.MessageBox.Show(this, "ISO表单以不存在！");
            BindData();
            //bll.Delete(ID);
            //gridView.OnBind();
        }
        private string GetSelIDlist()
        {
            string idlist = "";
            bool BxsChkd = false;
            for (int i = 0; i < gridView.Rows.Count; i++)
            {
                CheckBox ChkBxItem = (CheckBox)gridView.Rows[i].FindControl("checkboxname");
                if (ChkBxItem != null && ChkBxItem.Checked)
                {
                    BxsChkd = true;
                    //#warning 代码生成警告：请检查确认Cells的列索引是否正确
                    if (gridView.DataKeys[i].Value != null)
                    {
                        idlist += gridView.DataKeys[i].Value.ToString() + ",";
                    }
                }
            }
            if (BxsChkd)
            {
                idlist = idlist.Substring(0, idlist.LastIndexOf(","));
            }
            return idlist;
        }
        #endregion

        protected void btnSearch_Click(object sender, ImageClickEventArgs e)
        {
            BindData();
        }
    }
}